﻿namespace CRM.DataAccess.DAOs
{
    using System.Collections.Generic;
    using System.Data.Entity;
    using CRM.DataAccess.Entities;
    using System.Linq;
    using System.Data.Entity.Validation;
    using System.Diagnostics;
    using System;

    public partial class UserDAO : DbContext
    {
        public UserDAO()
            : base("name=Entities")
        {

        }
        public DbSet<USER> USERS { get; set; }
        public DbSet<USERS_LOGINS> USERS_LOGINS { get; set; }
        public DbSet<USER_DETAIL> USER_DETAIL { get; set; }

        /// Lists all.
        public List<USER> ListAll()
        {
            try
            {
                var userQuery = from u in USERS
                                select u;
                List<USER> users = userQuery.ToList();
                if (users.Count > 0)
                    return users;
                return null;
            }
            catch
            {
                return null;
            }
        }
        //Get User by RoleID
        public List<USER> GetUserByRoleID(long ID)
        {
            try
            {
                var user = from u in USERS
                           where u.ROLE_ID == ID
                           select u;
                List<USER> us = user.ToList();
                if (us.Count > 0)
                    return us;
                return null;
            }
            catch
            {
                return null;
            }
        }
        //Get User by ID
        public USER GetUserByID(long ID)
        {
            try
            {
                var userQuery = from u in USERS
                                where u.ID == ID
                                select u;
                List<USER> users = userQuery.ToList();
                if (users.Count > 0)
                    return users[0];
                return null;
            }
            catch
            {
                return null;
            }
        }
        //Get User by Username
        public USER GetUserByUsername(string Username)
        {
            try
            {
                var userQuery = from u in USERS
                                where u.USER_NAME == Username
                                select u;
                List<USER> users = userQuery.ToList();
                if (users.Count > 0)
                    return users[0];
                return null;
            }
            catch
            {
                return null;
            }
        }
       //Add new User
        public int AddNewUser(USER user)
        {
            try
            {
                this.USERS.Add(user);
                this.SaveChanges();
                return 1;
            }
            catch
            {
                return -1;
            }
        }
        //Delete user
        public int DeleteUser(long userID)
        {
            try
            {
                USERS.RemoveRange(USERS.Where(x => x.ID == userID));
                this.SaveChanges();
                return 1;
            }
            catch
            {
                return -1;
            }
        }
        //update USerDETAIL
        public int UpdateUserDetail(USER_DETAIL userDe)
        {
            try
            {
                var original = USER_DETAIL.Find(userDe.UserID);
                if (original != null)
                {
                    Entry(original).CurrentValues.SetValues(userDe);
                    SaveChanges();
                    return 1;
                }
                return -1;
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                                validationError.PropertyName,
                                                validationError.ErrorMessage);
                    }
                }
                return -1;
            }
        }
        //Update user
        public int UpdateUser(USER user)
        {
            try
            {
                var original = USERS.Find(user.ID);
                if (original != null)
                {
                    Entry(original).CurrentValues.SetValues(user);
                    SaveChanges();
                    return 1;
                }
                return -1;
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                                validationError.PropertyName,
                                                validationError.ErrorMessage);
                    }
                }
                return -1;
            }
        }
        //Change password
        public int ChangePassword(USER user)
        {
            try
            {
                var original = USERS.Find(user.ID);
                if (original != null)
                {
                    USER newUser = original;
                    newUser.DATE_MODIFIED = DateTime.Now;
                    newUser.USER_HASH = user.USER_HASH;
                    Entry(original).CurrentValues.SetValues(newUser);
                    this.SaveChanges();
                    return 1;
                }
                return -1;
            }
            catch
            {
                return -1;
            }
        }
        //Check exist
        public int CheckExist(string username)
        {
            try
            {
                var userQuery = from u in USERS
                                where u.USER_NAME.ToUpper() == username.ToUpper()
                                select u;
                List<USER> users = userQuery.ToList();
                if (users.Count > 0)
                    return 1;
                return 0;
            }
            catch
            {
                return -1;
            }
        }
        //Login
        public USER UserLogin(string username, string userhash)
        {
            try
            {
                var userQuery = from u in USERS
                                where u.USER_NAME.ToUpper() == username.ToUpper() && u.USER_HASH == userhash
                                select u;
                List<USER> users = userQuery.ToList();
                if (users.Count > 0)
                    return users[0];
                return null;
            }
            catch
            {
                return null;
            }
        }
        //Insert login history
        public int LoginHistory(USERS_LOGINS userLogin)
        {
            try
            {
                this.USERS_LOGINS.Add(userLogin);
                this.SaveChanges();
                return 1;
            }
            catch
            {
                return -1;
            }
        }

        //Get User by Condition
        public List<USER_DETAIL> GetUserByCondition(string UserName, bool? isAdmin, string primaryemail, string officephone, long? RoleID)
        {
            try
            {
                var Query = from u in USER_DETAIL
                            where ((UserName != "" ? (u.USER_NAME.ToUpper().Contains(UserName.ToUpper())) : (true))
                            && (primaryemail != "" ? (u.PRIMARY_EMAIL.ToUpper().Contains(primaryemail.ToUpper())) : (true))
                            && (officephone != "" ? (u.PHONE_OFFICE.ToUpper().Contains(officephone.ToUpper())) : (true))
                            //(u.USER_NAME.ToUpper() == (UserName == "" ? u.USER_NAME.ToUpper() : UserName.ToUpper())
                      //          && u.PRIMARY_EMAIL.ToUpper() == (primaryemail == "" ? u.PRIMARY_EMAIL.ToUpper() : primaryemail.ToUpper())
                          //      && u.PHONE_OFFICE.ToUpper() == (officephone == "" ? u.PHONE_OFFICE.ToUpper() : officephone.ToUpper())
                                && u.IS_ADMIN == (isAdmin == null ? u.IS_ADMIN : isAdmin)
                                && u.ROLE_ID == (RoleID == null ? u.ROLE_ID : RoleID))
                            select u;
                List<USER_DETAIL> us = Query.AsNoTracking().ToList();
                if (us.Count > 0)
                    return us;
                return null;
            }
            catch
            {
                return null;
            }
        }
        //Get User detail by ID
        public USER_DETAIL GetUserDetailByID(long id)
        {
            try
            {
                var Query = (from u in USER_DETAIL
                            where u.UserID == id
                            select u).AsNoTracking().FirstOrDefault<USER_DETAIL>();
                return Query as USER_DETAIL;
            }
            catch
            {
                return null;
            }
        }
    }
}
